//
//  HPDetailTableViewController.m
//  WWTQ
//
//  Created by JP on 2018/10/31.
//  Copyright © 2018年 Jqert. All rights reserved.
//

#import "HPDetailTableViewController.h"

#import "TemperatureTableViewCell.h"
#import "OtherTableViewCell.h"
#import "AfterDayTableViewCell.h"

#import "DataObjectModel.h"
#import "ForecastModel.h"

#import <MJRefresh.h>
#import <MJExtension.h>
#import "NetworkTool.h"

@interface HPDetailTableViewController ()

@property (nonatomic, strong) DataObjectModel *dataModel;

@end

static NSString *TemperatureTableViewCellID = @"TemperatureTableViewCellID";
static NSString *OtherTableViewCellID = @"OtherTableViewCellID";
static NSString *AfterDayTableViewCellID = @"AfterDayTableViewCellID";

@implementation HPDetailTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initBase];
    
    [self setUpTableView];
    
    [self addMJRefresh];
}

- (void)initBase {
    self.dataModel = [[DataObjectModel alloc] init];
}

- (void)setUpTableView {
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
}

- (void)addMJRefresh {
    MJRefreshNormalHeader *header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (![[self getInternetStatus] isEqualToString:@"notReachable"]) {
            [self getWeatherDate];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView.mj_header endRefreshing];
                buildErrorSVP(@"当前没有网络，请联网后再试");
            });
        }
    }];
    header.stateLabel.textColor = [UIColor whiteColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor whiteColor];
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
}

- (void)getWeatherDate {
    /*
     *天气请求调用 */
     [NetworkTool requestWeatherMessage:self.cityCode successBlock:^(id responseBody) {
         NSDictionary *dict = [NSDictionary dictionaryWithDictionary:responseBody];
         if ([dict[@"status"] integerValue] == 200) {
             NSDictionary *dictData = dict[@"data"];
             self.dataModel = [DataObjectModel mj_objectWithKeyValues:dictData];
             [self.tableView reloadData];
             
             ForecastModel *currentDayModel = self.dataModel.forecast.firstObject;
             
             NSMutableArray *cityMutArr = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"AllCityArr"]];
            
             NSDictionary *oldDict = self.allCityArr[self->_indexCity];
             
             NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
             
             [mutDict setObject:currentDayModel.high forKey:@"high"];
             [mutDict setObject:currentDayModel.low forKey:@"low"];
             [mutDict setObject:currentDayModel.type forKey:@"type"];
             
             NSDictionary *newDict = [NSDictionary dictionaryWithDictionary:mutDict];
             
             //删除之前行的数据
             [cityMutArr removeObject:oldDict];
             // 插入数据到新的位置
             [cityMutArr insertObject:newDict atIndex:self->_indexCity];
             self.allCityArr = [NSArray arrayWithArray:cityMutArr];
             
             [[NSUserDefaults standardUserDefaults] setObject:self.allCityArr forKey:@"AllCityArr"];
             [[NSUserDefaults standardUserDefaults] synchronize];
             if (self.isSelect) {
                 if (self.delegate && [self.delegate respondsToSelector:@selector(sendIsFristSelect)]) {
                     [self.delegate sendIsFristSelect];
                 }
             }
         } else {
             buildErrorSVP(@"服务器异常,请稍后再试");
         }
         [self.tableView.mj_header endRefreshing];
     } failureBlock:^(NSString *error) {
         [self.tableView.mj_header endRefreshing];
     }];
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.dataModel.forecast.count < 1) {
        return 1;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) return 2;
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) return 0.66 * (ScreenH - SafeAreaTopHeight);
        return 0.34 * (ScreenH - SafeAreaTopHeight);
    }
    return 230;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) return 0;
    else return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    headerView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TemperatureTableViewCellID];
            if (!cell){
                cell = [[TemperatureTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TemperatureTableViewCellID];
            }
            if (self.dataModel.forecast.count > 0) {
                cell.dataModel = self.dataModel;
            }
            return cell;
        } else {
            OtherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OtherTableViewCellID];
            if (!cell) {
                cell = [[OtherTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:OtherTableViewCellID];
            }
            if (self.dataModel.forecast.count > 0) {
                cell.dataModel = self.dataModel;
            }
            return cell;
        }
    }
    AfterDayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:AfterDayTableViewCellID];
    if (!cell) {
        cell = [[AfterDayTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AfterDayTableViewCellID];
    }
    cell.dataModel = self.dataModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offset = scrollView.contentOffset.y;
    CGFloat alpha = offset / 200;
    if (self.delegate && [self.delegate respondsToSelector:@selector(sendContentOffsetY:)]) {
        [self.delegate sendContentOffsetY:offset];
    }
    if (alpha > 0.6) {
        alpha = 0.6;
    } else if (offset < 0) {
        alpha = 0;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(sendScrollViewAlpha:)]) {
        [self.delegate sendScrollViewAlpha:alpha];
    }
}

#pragma mark - 获取网络状态
- (NSString *)getInternetStatus {
    Reachability *reachability  = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"wifi";
    switch (internetStatus) {
        case ReachableViaWiFi:
            net = @"wifi";
            break;
        case ReachableVia2G:
            net = @"2G";
            break;
        case ReachableVia3G:
            net = @"3G";
            break;
        case ReachableVia4G:
            net = @"4G";
            break;
            
        case NotReachable:
            net = @"notReachable";
        default:
            break;
    }
    return net;
}

@end
